﻿ 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Principal;
using System.Text;

namespace FB.Membership.Principal
{
    public interface IFBPrincipal : IPrincipal
    {
        List<Permission> Permission { get; }
    }


    public class FBPrincipal : IFBPrincipal
    {
        string _AppKey = FB.Helpers.AppSettingsBase.AppKey;

        public string AppKey { get { return _AppKey; } }
        public IIdentity Identity { get;  private set; }
        public FBIdentity FBIdentity { get { return (IdentityIsReady()) ? (FBIdentity)Identity : new FBIdentity(); } }
        public List<Permission> Permission
        {
            get
            {
                return PermissionManager.PermissionSession ?? new List<Permission>();
            }
        }

        public FB.Data.Models.EmployeeInfo EmployeeInfo
        {
            get
            {
                return FB.Providers.EmployeeInfoManager.EmployeeSession;
            }
        }


        public FBPrincipal()
        {
            Identity = new FBIdentity();
        }

        public FBPrincipal(IIdentity identity)
        {
            Identity = identity;
        }

        public bool IsInRole(string role)
        {
            return AspNetRoleProviderWrapper.RoleSession != null && AspNetRoleProviderWrapper.RoleSession.Contains(role, StringComparer.CurrentCultureIgnoreCase);
        }


        public bool HasThisAppService(string ApplicationKey)
        {
            List<string> serviceList;
            if (Identity is FBIdentity && ((FBIdentity)Identity).Services != null)
            {
                serviceList = ((FBIdentity)Identity).Services;
            }
            else
            {
                var membership = new AspNetMembershipProviderWrapper();
                serviceList = membership.GetService(Identity.Name);
            }

            return serviceList.Contains(ApplicationKey, StringComparer.InvariantCultureIgnoreCase);
        }
        
        public bool HasFlag<P>(P flag)
        {
            return PermissionManager.Validate<P>(Permission, flag);
        }
        public bool HasModule<M>(M module)
        {
            return PermissionManager.ValidateModule<M>(Permission, module);

        }

        public bool HasAnyFlagOf<P>()
        {
            return PermissionManager.AnyOf<P>(Permission);
        }


        bool IdentityIsReady()
        {
            return (Identity != null && Identity is FBIdentity && Identity.IsAuthenticated);
            //return Identity.IsAuthenticated;
        }
    }


}
